﻿// Copyright 2008 William P. Hickey Jr. and William U. Walker
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//     
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//  
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.IO;

namespace CSReporter
{
    public partial class MessageForm : Form
    {
        private ConfigList configure;
        private StationList stations;
        private int printMore;
        private string toCall;
        private string viaList;
        private string[] message;
        private string[] msgId;

        public string ToCall
        {
            get { return toCall; }
        }

        public string ViaList
        {
            get { return viaList; }
        }

        public string[] Messages
        {
            get { return message; }
        }

        public string[] MessageID
        {
            get { return msgId; }
        }

        public MessageForm()
        {
            InitializeComponent();
        }

        public MessageForm(string toCall)
        {
            InitializeComponent();
            toTextBox.Text = toCall.Trim();
        }

        public MessageForm(string toCall, string message)
        {
            InitializeComponent();
            toTextBox.Text = toCall.Trim();
            messageRichTextBox.Text = message.Trim();
        }

        private void MessageForm_Load(object sender, EventArgs e)
        {
            // Get the ConfigList object.
            configure = ConfigList.GetConfigList();
            // Get the StationList object.
            stations = StationList.GetStationList();
            // Use the stations object as the datasource for the listbox.
            stationsListBox.DataSource = stations;
            // Display the call signs from the stations list.
            stationsListBox.DisplayMember = "CallSign";
            // Insert the configured default digipath into index 0 of the drop down list.
            digiPathComboBox.Items.Insert(0, configure[0].DigiPath.Trim().ToUpper());
        }

        private void sendToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DateTime curTime = DateTime.Now;

            // Replace new line characters with a space.
            messageRichTextBox.Text = messageRichTextBox.Text.Replace("\n", " ");
            // Remove all other non-printable characters.
            messageRichTextBox.Text = Regex.Replace(messageRichTextBox.Text, "[\u0000-\u001F\u0080-\u00FF]", "");
            // Determine how many 67 byte messages must be sent.
            int segments = (int)Math.Ceiling((double)messageRichTextBox.Text.Trim().Length / 67);

            if (toTextBox.Text.Trim().Length > 0 & segments > 0)
            {
                message = new string[segments];
                msgId = new string[segments];
                toCall = toTextBox.Text.Trim();
                viaList = digiPathComboBox.Text.Trim();
                Radio radio = Radio.GetRadio();

                for (int index = 0; index < segments; index++)
                {
                    // Format the message.
                    message[index] = ":" + toTextBox.Text.Trim().PadRight(9, ' ') + ":" + messageRichTextBox.Text.Trim().Substring((index * 67), Math.Min(67, messageRichTextBox.Text.Trim().Length - (index * 67)));
                    if (ackCheckBox.Checked)
                    {
                        // Create the message id string.
                        msgId[index] = String.Format("{0:X}", (curTime.Hour * 10000) + (curTime.Minute * 1000) + (curTime.Second + index));
                        // Append the message id delimiter and the message id to the end of the message.
                        message[index] += "{" + msgId[index];
                    }
                    // Send the message.
                    if(radio.IsOpen)
                        radio.SendMessage(0, 6, ToCall.ToUpper(), viaList.ToUpper(), message[index], msgId[index]);
                }
                Close();
            }
        }

        private void sendToolStripButton_Click(object sender, EventArgs e)
        {
            sendToolStripMenuItem_Click(sender, e);
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Change or set the Type field to that of the Drafts folder.
        }

        private void saveToolStripButton_Click(object sender, EventArgs e)
        {
            saveToolStripMenuItem_Click(sender, e);
        }

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StreamWriter fileStream;

            saveFileDialog.ShowDialog();

            if (saveFileDialog.FileName.Length > 0)
            {
                switch (saveFileDialog.FilterIndex)
                {
                    case 1: // Rich Text file
                        messageRichTextBox.SaveFile(saveFileDialog.FileName, RichTextBoxStreamType.RichText);
                        break;
                    case 2: // Text file
                        fileStream = new StreamWriter(saveFileDialog.FileName);
                        fileStream.Write(messageRichTextBox.Text);
                        fileStream.Close();
                        break;
                }
            }
        }

        private void stationsListBox_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            toTextBox.Text = stationsListBox.Text;
        }

        private void pageSetupToolStripMenuItem_Click(object sender, EventArgs e)
        {
            pageSetupDialog.ShowDialog();
        }

        private void printPreviewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            printPreviewDialog.ShowDialog();
        }

        private void printToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (printDialog.ShowDialog() == DialogResult.OK)
                printToolStripButton_Click(this, null);
        }

        private void printToolStripButton_Click(object sender, EventArgs e)
        {
            // Show the print dialog.
            printDialog.ShowDialog();
        }

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Close the editor.
            Close();
        }

        private void messageRichTextBox_TextChanged(object sender, EventArgs e)
        {
            int len = messageRichTextBox.Text.Trim().Length;
            int curPos = messageRichTextBox.SelectionStart;

            if (len > 67)
            {
                messageRichTextBox.SelectionStart = 67;
                messageRichTextBox.SelectionLength = Math.Min(67, messageRichTextBox.Text.Trim().Length - 67);
                messageRichTextBox.SelectionColor = Color.DarkRed;
                messageRichTextBox.DeselectAll();
            }
            if (len > 134)
            {
                messageRichTextBox.SelectionStart = 135;
                messageRichTextBox.SelectionLength = Math.Min(67, messageRichTextBox.Text.Trim().Length - 134);
                messageRichTextBox.SelectionColor = Color.IndianRed;
                messageRichTextBox.DeselectAll();
            }
            if (len > 201)
            {
                messageRichTextBox.SelectionStart = 202;
                messageRichTextBox.SelectionLength = messageRichTextBox.Text.Trim().Length - 201;
                messageRichTextBox.SelectionColor = Color.Red;
                messageRichTextBox.DeselectAll();
            }
            messageRichTextBox.SelectionStart = curPos;
        }

        private void PrintDocument_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
        {
            // Initialize printMore.
            printMore = 0;
        }

        private void PrintDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            // Print the content of RichTextBox and record the last character printed.
            printMore = messageRichTextBox.Print(printMore, messageRichTextBox.TextLength, e);

            // Check for more pages.
            if (printMore < messageRichTextBox.Text.Length)
                e.HasMorePages = true;
            else
                e.HasMorePages = false;
        }
    }
}
